package ru.stepuk.modern.nodes;

import javax.swing.ImageIcon;
import javax.swing.JDialog;
import ru.stepuk.modern.InvalidModelException;
import ru.stepuk.modern.Model;
import ru.stepuk.modern.Path;
import ru.stepuk.modern.Request;
import ru.stepuk.modern.nodes.servers.Interruptive;

/**
 *
 * @author ivan
 */
public class RequestFilter extends Node {

    private Interruptive server;
    Path a;
    Path b;

    {
        icon = new ImageIcon(getClass().getResource("/images/c_served.png"));
    }

    public RequestFilter(Model model) {
        super(model);
    }

    @Override
    public void processRequest(Request request) {
        if (a.getWeight() < b.getWeight()) {
            Path c = a;
            a = b;
            b = c;
        }

        if (server.lastServeSuccessfull()) {
            model.getNodeByPath(a).processRequest(request);
        } else {
            model.getNodeByPath(b).processRequest(request);
        }
    }

    @Override
    public void validate() throws InvalidModelException {
        server = null;
        a = null;
        b = null;

        if (model.getPreviousNodes(this).size() != 1) {
            throw new InvalidModelException("Illegal input");
        } else {
            try {
                server = (Interruptive) model.getPreviousNodes(this).toArray()[0];
            } catch (ClassCastException ex) {
                throw new InvalidModelException("Bad input, need server");
            }
        }

        if (model.getOutcome(this).size() != 2) {
            throw new InvalidModelException("need 2 outs!");
        } else {
            a = (Path) model.getOutcome(this).toArray()[0];
            b = (Path) model.getOutcome(this).toArray()[1];
            if (a.getWeight() == b.getWeight()) {
                throw new InvalidModelException("same weights");
            }
        }
    }

    @Override
    public JDialog getPropertiesDialog() {
        return null;
    }
}
